import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/model/user_info_entity.dart';
import 'package:tender_flutter/page/person/model/tixian_history_entity.dart';
import 'package:tender_flutter/providers/provider.dart';
import 'package:tender_flutter/providers/user_profile.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';
import 'package:tender_flutter/widgets/sticky_tabbar_delegate.dart';

import 'api/api_person.dart';

class TiXianHistoryPage extends StatefulWidget {
  @override
  _TiXianHistoryPageState createState() => _TiXianHistoryPageState();
}

class _TiXianHistoryPageState extends State<TiXianHistoryPage> {
  /// 刷新组件
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<TixianHistoryEntity>> _listFuture;

  LoadState _loadState = LoadState.State_Loading;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  /// 列表数据
  List<TixianHistoryDataList> _dataLists = [];

  UserInfoEntity _userInfoEntity;

  ///刷新数据
  Future _refresh() async {
    if (_refreshController.isRefresh) {
      page = 1;
    }
    if (_refreshController.isLoading) {
      page += 1;
    }

    setState(() {
      _listFuture = _getData();
    });
  }

  /// 获取用户信息
  Future _getUserInfo() async {
    var response = await ApiPerson.getUserInfo<UserInfoEntity>();
    _userInfoEntity = response.result;
    Store.value<UserProfileInfo>(context).setUserInfo(_userInfoEntity);
    if (_refreshController.isRefresh) {
      _refreshController.refreshCompleted();
    }
  }

  /// 获取数据
  Future<ApiResponse<TixianHistoryEntity>> _getData() async {
    var response = await ApiPerson.getTiXianHistory<TixianHistoryEntity>(
      page: page,
      pageCount: pageCount,
    );
    return response;
  }

  FutureBuilder<ApiResponse<TixianHistoryEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _listFuture,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<TixianHistoryEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              TixianHistoryEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            bgColor: ThemeColors.colorWhite,
            state: _loadState,
            successWidget: _initList(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _listFuture = _getData();
    WidgetsBinding.instance.addPostFrameCallback((mag) {
      _getUserInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _initBody(),
    );
  }

  /// 导航栏
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("返佣提现", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  /// 内容体
  Widget _initBody() {
    return Container(
        child: Column(children: [
      Expanded(
          child: NestedScrollView(
        headerSliverBuilder: (context, innerScrolled) => <Widget>[
          SliverOverlapAbsorber(
            // 传入 handle 值，直接通过 `sliverOverlapAbsorberHandleFor` 获取即可
            handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
            sliver: SliverAppBar(
              backgroundColor: Colors.transparent,
              elevation: 1,
              automaticallyImplyLeading: false,
              expandedHeight: ScreenAdapter.height(280),
              stretch: true,
              flexibleSpace: FlexibleSpaceBar(
                background: _initTopView(),
                collapseMode: CollapseMode.parallax,
                stretchModes: [
                  StretchMode.zoomBackground,
                  StretchMode.blurBackground,
                  StretchMode.fadeTitle,
                ],
              ),
            ),
          ),
          SliverPersistentHeader(
            pinned: true,
            delegate: StickyTabBarDelegate(
              minHeight: ScreenAdapter.height(80),
              maxHeight: ScreenAdapter.height(80),
              child: _initTitleView(),
            ),
          ),
        ],
        body: _buildFutureBuilder(),
      )),
      _initTiXianBtn()
    ]));
  }

  /// 提现余额视图
  Widget _initTopView() {
    return Consumer(
        builder: (BuildContext ctx, UserProfileInfo profileInfo, Widget child) {
      return Container(
          width: double.infinity,
          // height: ScreenAdapter.height(280),
          margin: EdgeInsets.all(ScreenAdapter.width(25)),
          padding: EdgeInsets.only(
              left: ScreenAdapter.width(50),
              right: ScreenAdapter.width(50),
              top: ScreenAdapter.width(40),
              bottom: ScreenAdapter.width(40)),
          //设置背景图片
          decoration: new BoxDecoration(
            image: DecorationImage(
              image: AssetImage(RPath.imgPath + "img_tixina_top_bg.png"),
              fit: BoxFit.fill,
            ),
          ),
          child:
              Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text(
                "余额（元）",
                style: TextStyle(
                    color: ThemeColors.colorType61,
                    fontSize: ScreenAdapter.sp(24),
                    fontWeight: FontWeight.w500),
              ),
              SizedBox(height: ScreenAdapter.height(20)),
              Text(
                profileInfo.userInfo.money ?? "0",
                style: TextStyle(
                    color: ThemeColors.colorWhite,
                    fontSize: ScreenAdapter.sp(50),
                    fontWeight: FontWeight.bold),
              )
            ]),
            Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text(
                "累计收益（元）",
                style: TextStyle(
                    color: ThemeColors.colorType61,
                    fontSize: ScreenAdapter.sp(24),
                    fontWeight: FontWeight.w500),
              ),
              SizedBox(height: ScreenAdapter.height(20)),
              Text(
                profileInfo.userInfo.inMoney ?? "0",
                style: TextStyle(
                    color: ThemeColors.colorWhite,
                    fontSize: ScreenAdapter.sp(36),
                    fontWeight: FontWeight.bold),
              ),
              SizedBox(height: ScreenAdapter.height(40)),
              Text(
                "满${profileInfo.userInfo.txBeginMoney}元可提现",
                style: TextStyle(
                    color: ThemeColors.colorType61,
                    fontSize: ScreenAdapter.sp(24),
                    fontWeight: FontWeight.w500),
              )
            ])
          ]));
    });
  }

  /// 标题
  Widget _initTitleView() {
    return Container(
        width: double.infinity,
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
        color: ThemeColors.colorWhite,
        child:
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Expanded(
              child: Text(
            "提现记录",
            style: TextStyle(
                color: ThemeColors.colorType1,
                fontSize: ScreenAdapter.sp(35),
                fontWeight: FontWeight.bold),
          )),
          // InkWell(
          //     onTap: () {
          //       LRouter.navigatorCtx(context).push(Routes.supplierListMorePage);
          //     },
          //     child: Row(children: [
          //       Text(
          //         "查看更多",
          //         style: TextStyle(
          //             color: ThemeColors.colorType3,
          //             fontSize: ScreenAdapter.sp(26),
          //             fontWeight: FontWeight.bold),
          //       ),
          //       Icon(Icons.read_more, color: ThemeColors.colorType3),
          //     ]))
        ]));
  }

  /// 提现按钮
  Widget _initTiXianBtn() {
    return Consumer(
        builder: (BuildContext ctx, UserProfileInfo profileInfo, Widget child) {
      return Container(
        margin: EdgeInsets.all(ScreenAdapter.width(30)),
        width: double.infinity,
        height: ScreenAdapter.height(90),
        child: FlatButton(
          color: ThemeColors.colorType6,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(ScreenAdapter.width(14)),
          ),
          child: Text(
            "提现",
            style: TextStyle(
                color: ThemeColors.colorWhite, fontSize: ScreenAdapter.sp(30)),
          ),
          onPressed: () {
            if (profileInfo.userInfo.money >
                double.parse(profileInfo.userInfo.txBeginMoney)) {
              LRouter.navigatorCtx(context).push(Routes.tiXianPage);
            } else {
              ToastUtils.show("提现金额不足,无法提现");
            }
          },
        ),
      );
    });
  }

  /// 主体内容列表
  Widget _initList() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _refresh,
        onLoading: _refresh,
        child: ListView.separated(
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            TixianHistoryDataList model = _dataLists[index];
            return _getCell(model: model, onTap: () {});
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(color: ThemeColors.colorType49);
          },
        ));
  }

  /// Item列表
  Widget _getCell({TixianHistoryDataList model, GestureTapCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: EdgeInsets.symmetric(
            horizontal: ScreenAdapter.width(30),
            vertical: ScreenAdapter.height(15)),
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    "订单编号：${model.outordercode}",
                    style: TextStyle(
                        color: ThemeColors.colorType14,
                        fontSize: ScreenAdapter.sp(26),
                        fontWeight: FontWeight.w500),
                  ),
                ],
              ),
              SizedBox(height: ScreenAdapter.height(20)),
              Text(
                model.createDate,
                style: TextStyle(
                    color: ThemeColors.colorType26,
                    fontSize: ScreenAdapter.sp(26)),
              ),
              SizedBox(height: ScreenAdapter.height(20)),
              Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                Text("提现${model.money ?? "0.0"}元",
                    textAlign: TextAlign.left,
                    maxLines: 2,
                    softWrap: true,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontWeight: FontWeight.w500,
                      fontSize: ScreenAdapter.sp(28),
                    )),
                Text(
                  model.txStatus,
                  style: TextStyle(
                      color: ThemeColors.colorType16,
                      fontSize: ScreenAdapter.sp(28),
                      fontWeight: FontWeight.w500),
                ),
              ]),
            ],
          ),
        ),
      ),
    );
  }
}
